package com.dabai.iot.core.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dabai.common.redis.utils.RedisUtils;
import com.dabai.common.tenant.helper.TenantHelper;
import com.dabai.iot.core.cache.CacheKey;
import com.dabai.iot.core.entity.AlarmListenerEntity;
import com.dabai.iot.core.mapper.AlarmListenerMapper;
import com.dabai.iot.core.service.IAlarmListenerService;
import org.springframework.stereotype.Service;

/**
 * 告警监听条件 Service 实现类
 *
 * @author kev1n
 */
@Service
public class AlarmListenerServiceImpl extends ServiceImpl<AlarmListenerMapper, AlarmListenerEntity> implements IAlarmListenerService {

    @Override
    public AlarmListenerEntity getAlarmListenerCacheByAlarmId(Long alarmId) {
        String cacheKey = CacheKey.getAlarmListenerKey(alarmId);
        AlarmListenerEntity alarmListenerCache = TenantHelper.ignore(() -> RedisUtils.getCacheObject(cacheKey));
        if (alarmListenerCache != null) {
            return alarmListenerCache;
        }

        final AlarmListenerEntity alarmListener = this.lambdaQuery()
            .eq(AlarmListenerEntity::getAlarmId, alarmId)
            .one();
        if (alarmListener != null) {
            alarmListenerCache = alarmListener;
            TenantHelper.ignore(() -> RedisUtils.setCacheObject(cacheKey, alarmListener));
        }

        return alarmListenerCache;
    }

    @Override
    public void removeAlarmListener(Long alarmId) {
        this.remove(Wrappers.<AlarmListenerEntity>query().lambda().eq(AlarmListenerEntity::getAlarmId, alarmId));
        // 删除缓存
        String cacheKey = CacheKey.getAlarmListenerKey(alarmId);
        TenantHelper.ignore(() -> RedisUtils.deleteObject(cacheKey));
    }

}
